package org.example.service;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.OSSClient;
import lombok.extern.slf4j.Slf4j;
import org.example.R.R;
import org.example.config.OSSConfig;
import org.example.entity.po.OSSPO;
import org.example.entity.vo.OSSFileVO;
import org.example.mapper.OSSMapper;
import org.example.utils.TimeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Map;

@Service
@Slf4j
public class ExService {

    @Autowired
    private OSSMapper ossMapper;

    @Autowired
    private OSSClient ossClient;

    @Autowired
    private OSSConfig ossConfig;
    private String bucketName = "wpjd";
    private String OSS_PREFIX = "http://wpjd.oss-cn-qingdao.aliyuncs.com";

    public String uploadFile(String filename, InputStream inputStream) {
        ossClient.putObject(bucketName, filename, inputStream);
        // 返回文件的URL
        return ossClient.generatePresignedUrl(bucketName, filename, new Date(System.currentTimeMillis() + 3600 * 1000)).toString();
    }

    public R uploadOSS(MultipartFile ossFile) {
        // 获取文件的输入流
        InputStream inputStream = null;

        try {
            inputStream = ossFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("ossUpload:" + e.getMessage());
        }
        String filename = ossFile.getOriginalFilename();
        String fileUrl = this.uploadFile(filename, inputStream);

        OSSFileVO vo = new OSSFileVO();
        vo.setOssFileName(filename);
        vo.setOssFileUrl(OSS_PREFIX + "/" + filename);
        String fileType = getFileType(filename);
        vo.setOssFileType(fileType);
        vo.setOssHeader(fileUrl.replaceAll(OSS_PREFIX, ""));


        OSSPO po = new OSSPO();
        BeanUtils.copyProperties(vo, po);
        po.setId(IdUtil.getSnowflakeNextId());
        po.setCreateTime(TimeUtils.getCurrentTime());
        ossMapper.insert(po);

        return R.success("上传OSS成功!").setData(po);
    }

    public OSSFileVO detail(Long id) {
        OSSFileVO ossFileVO = ossMapper.detail(id);
        return ossFileVO;
    }

    public static String getFileType(String fileName) {
        int dotIndex = fileName.lastIndexOf(".");
        if (dotIndex > 0 && dotIndex < fileName.length() - 1) {
            return fileName.substring(dotIndex + 1);
        }
        return "";
    }
}
